import useWs from "./useWs";
import { PxNotification } from "px-ui";
import AlarmList from "@/components/AlarmDialog/components/List.vue";
import { h, nextTick } from "vue";

let PxNotificationInstance = null;
let mesgQueue = [];
let timeFlag = null;
const userInfo = JSON.parse(localStorage.getItem("userInfo"));

export default function useGlobelWarn() {
  try {
    useWs({
      queryStr: "alarmWs",
      onmessage: open
    });
    //模拟数据
    // let msg = {
    //   alarmAckStatus: "DONE",
    //   alarmContent: "一级报警",
    //   alarmLevel: "二级报警",
    //   alarmStatus: "ON",
    //   alarmTime: "2024-10-23 10:46:35",
    //   buildingId: "",
    //   className: "GAS",
    //   factoryId: "",
    //   point: "STIC_CDS_H2SO4_01UP_LEAK.ERROR.ALM.VALUE",
    //   realityValue: "1",
    //   roomId: "",
    //   twinId: "",
    //   twinName: ""
    // };
    // open(msg);
  } catch (e) {
    console.error(e);
  }
}
function open(data) {
  const { accountNameList, factoryId, className } = data;
  const facCode = localStorage.getItem("facCode") || "";
  let userClassName = JSON.parse(localStorage.getItem("classList")) || [];
  if (userClassName?.length > 0) {
    const res = [];
    userClassName.forEach(item => {
      res.push(item.code);
    });
    userClassName = res;
  }
  if (facCode && facCode !== factoryId) return;
  if (!userClassName.includes(className)) return;
  if (accountNameList?.length > 0) {
    if (!accountNameList.includes(userInfo.username)) return;
  }
  if (!timeFlag) {
    mesgQueue.push(data);
    timeFlag = setTimeout(() => {
      let msg = mesgQueue.pop();
      mesgQueue = [];

      open(msg);
      timeFlag = null;
    }, 2000);
    return;
  } else if (mesgQueue.length > 0) {
    mesgQueue.push(data);
    return;
  }
  if (PxNotificationInstance && PxNotificationInstance.close) {
    PxNotificationInstance.close();
  }
  nextTick(() => {
    PxNotificationInstance = PxNotification({
      title: "报警通知",
      dangerouslyUseHTMLString: true,
      message: h(AlarmList, { ...data }),
      position: "bottom-right"
    });
  });
}
